package com.carrentalssm.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.carrentalssm.entity.AdminUser;
import com.carrentalssm.entity.User;
import com.carrentalssm.service.AdminUserService;
import com.carrentalssm.service.UserService;

/**
 * 登录Controller
 */
@Controller
@RequestMapping("/login")
public class LoginController {

	@Autowired
	private UserService userService;
	
	@Autowired
	private AdminUserService adminUserService;
	
	@RequestMapping(value = "", method = RequestMethod.POST)
	public String login(
			@RequestParam("username") String username, 
			@RequestParam("password") String password, 
			@RequestParam("userType") String userType,
			Model model,
			HttpServletRequest request) {
		try {
			if (userType.equals("a")) {
				AdminUser selectByNamePwd = adminUserService.selectByNamePwd(username, password);
				if (selectByNamePwd != null) {
					System.out.println("登录成功");
					request.getSession().setAttribute("user", selectByNamePwd);
					return "redirect:/admin.jsp";
				} else {
					System.out.println("登录失败");
					model.addAttribute("errorMsg", "用户名或密码错误");
					return "login";
				}
			} else if (userType.equals("u")) {
				User selectByNamePwd = userService.selectByNamePwd(username, password);
				if (selectByNamePwd != null) {
					System.out.println("登录成功");
					request.getSession().setAttribute("user", selectByNamePwd);
					return "redirect:/index.jsp";
				} else {
					System.out.println("登录失败");
					model.addAttribute("errorMsg", "用户名或密码错误");
					return "login";
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("登录失败");
		model.addAttribute("errorMsg", "系统异常");
		return "login";
	}
	
}
